package com.goods.redis2msyql.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * The system configure reader.
 * 
 * @author Jianquan Wang
 *
 */
public class SystemConfigureReader {
	private Logger logger = LoggerFactory.getLogger(SystemConfigureReader.class);

	private Properties systemProps = null;

	private long lastUpdateTime;

	private long interval = 5 * 60 * 1000L;

	private static SystemConfigureReader reader;

	private SystemConfigureReader() {
	}

	public static synchronized SystemConfigureReader getReader() {
		if (reader == null) {
			reader = new SystemConfigureReader();
			reader.refresh();
		}
		return reader;
	}

	public synchronized void refresh() {
		if (systemProps == null || System.currentTimeMillis() > lastUpdateTime + interval) {
			Properties props = new Properties();
			InputStream inputStream = null;
			try {
				inputStream = SystemConfigureReader.class.getResourceAsStream("/system.properties");
				props.load(inputStream);

				lastUpdateTime = System.currentTimeMillis();

				systemProps = props;
			} catch (IOException e) {
				logger.error("找不到资源：system.properties ", e);
			} finally {
				try {
					if (inputStream != null) {
						inputStream.close();
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	/**
	 * Read the configure item by the key.
	 * 
	 * @param key
	 * @return value
	 */
	public String getProperty(String key) {
		return systemProps.getProperty(key, "").trim();
	}

}
